import { Button, Modal } from "antd";
import { FC, ReactElement, useRef, useState } from "react";
import styled from "styled-components";
import {
  queryTodoList,
  Todo,
  addTodo,
  deleteTodo,
  updateTodo,
} from "../../../api/todo";
import useMount from "../../../hooks/useMount";
import { Container as RComponent } from "../TagManage";
import { scrollbar } from "../../../components/BUI/styled";
import { NotificationSuccess } from "../../common/Notification";

interface IProps {}

const TodoListManage: FC<IProps> = (): ReactElement => {
  const [todoList, setTodoList] = useState<Todo[]>([]);
  const [undoList, setUndoList] = useState<Todo[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const resultRef = useRef<HTMLInputElement>(null);
  const [resultTodo, setResultTodo] = useState<Todo | null>(null);

  useMount(() => {
    queryTodoList().then(({ data }) => {
      if (data && data.code === 0) {
        const todo: Todo[] = [];
        const undo: Todo[] = [];
        data.todoList.forEach(item => {
          item.result ? undo.push(item) : todo.push(item);
        });
        setTodoList(todo);
        setUndoList(undo);
      }
    });
  });

  const handleAddTodo = () => {
    const input = inputRef.current;
    if (input && input.value) {
      const { value: name } = input;
      const params = { name };

      addTodo(params).then(({ data }) => {
        if (data) {
          console.log(data);
          setTodoList(prev => [{ ...params, _id: data._id }, ...prev]);
          input.value = "";
        }
      });
    }
  };

  const handleDelete = (item: Todo) => async () => {
    const { data } = await deleteTodo({ id: item._id });
    console.log(data);
    if (!data) return;
    if (item.result) {
      setUndoList(prev => prev.filter(undo => undo._id !== item._id));
    } else {
      setTodoList(prev => prev.filter(todo => todo._id !== item._id));
    }
  };

  const handleSetResult = (todo: Todo) => () => {
    setResultTodo(todo);
  };

  const handleOk = async () => {
    const input = resultRef.current;
    if (input && input.value) {
      const result = input.value;
      const item = resultTodo as Todo;
      const { data } = await updateTodo({ _id: item._id, result });
      console.log(data);
      if (!data) return;
      //@ts-ignore
      setTodoList(prev => prev.filter(todo => todo._id !== item._id));
      setUndoList(prev => [{ ...item, result }, ...prev]);
      setResultTodo(null);
      NotificationSuccess({ message: "🎉完成一件,可喜可贺" });
    }
  };

  return (
    <Container>
      <section>
        <Input ref={inputRef} />
        <Button type='primary' onClick={handleAddTodo}>
          代办
        </Button>
      </section>
      <div>
        {todoList.map(item => (
          <div
            style={{
              background: `linear-gradient(
            45deg, #${Math.random().toString(16).slice(-6)}, transparent)`,
            }}
            key={item._id}
          >
            <h2>{item.name}</h2>
            <br />
            <Button type='ghost' onClick={handleDelete(item)}>
              删除
            </Button>
            <Button type='primary' ghost onClick={handleSetResult(item)}>
              解决
            </Button>
          </div>
        ))}
      </div>
      <div>
        {undoList.map(item => (
          <div
            style={{
              background: `linear-gradient(
          45deg, #${Math.random().toString(16).slice(-6)}, transparent)`,
            }}
            key={item._id}
          >
            <h2>{item.name}</h2>
            <span>{item.result}</span>
            <br />
            <Button type='ghost' onClick={handleDelete(item)}>
              删除
            </Button>
            <Button type='dashed' ghost onClick={handleSetResult(item)}>
              更改结果
            </Button>
          </div>
        ))}
      </div>
      <Modal
        title='🎉恭喜解决'
        visible={!!resultTodo}
        onCancel={() => setResultTodo(null)}
        onOk={handleOk}
      >
        <Input ref={resultRef} />
      </Modal>
    </Container>
  );
};

export default TodoListManage;

const Input = styled.input`
  border: none;
  width: 20rem;
  height: 3rem;
  margin: 0 1rem;
  padding-left: 1rem;
  background: #ccc;
`;

const Container = styled(RComponent)`
  display: flex;
  padding: 1rem;
  padding-top: 5rem;
  position: relative;

  & > div {
    display: flex;
    flex-direction: column;
    flex: 1;
    padding: 0.5rem;
    overflow: hidden scroll;
    ${scrollbar};
    & > div {
      margin: 0.5rem;
      box-shadow: 0 0 10px 2px #ccc;
      border-radius: 0.5rem;
      padding: 0.5rem;
      button {
        margin-right: 1rem;
      }
    }
  }
  ::after {
    content: "";
    position: absolute;
    bottom: 1rem;
    right: 50%;
    width: 2px;
    border-radius: 2px;
    height: calc(100% - 7rem);
    background: #999;
  }

  & > section {
    position: absolute;
    top: 0;
    left: 0;
    height: 4rem;
    background: #eee;
    width: 100%;
    box-shadow: 0 2px 10px 1px #ccc;
    display: flex;
    align-items: center;
    justify-content: center;

    & > button {
      height: 3rem;
      width: 6rem;
      font-weight: bold;
    }
  }
`;
